"""
AI服务API端点
提供AI服务相关的API接口，包括连接测试和服务状态查询。
"""

import logging
from fastapi import APIRouter, HTTPException, Depends
from typing import Dict, Any, Optional, List
from pydantic import BaseModel

from ..services.ai_service import ai_service
from ..services.content_generator import content_generator
from ..models import PPTRequest, SlideContent

logger = logging.getLogger(__name__)

router = APIRouter()


class AITestRequest(BaseModel):
    """AI连接测试请求模型"""
    test_message: Optional[str] = "连接测试"


class AIGenerateRequest(BaseModel):
    """AI生成请求模型"""
    topic: str
    requirements: Optional[str] = None
    slide_count: int = 10


class SlideGenerateRequest(BaseModel):
    """单个幻灯片生成请求模型"""
    title: str
    slide_type: str = "content"
    slide_number: int = 1
    context: Dict[str, Any] = {}


class VisualSuggestionRequest(BaseModel):
    """视觉元素建议请求模型"""
    slide_title: str
    slide_content: List[str]
    slide_type: str = "content"
    template_style: str = "professional"


class ContentOptimizeRequest(BaseModel):
    """内容优化请求模型"""
    slides: List[Dict[str, Any]]
    optimization_goals: Optional[List[str]] = None


@router.get("/ai/status")
async def get_ai_service_status():
    """
    获取AI服务状态
    
    Returns:
        Dict: AI服务状态信息
    """
    try:
        status = ai_service.get_service_status()
        return {
            "success": True,
            "status": status,
            "message": "AI服务状态获取成功"
        }
    except Exception as e:
        logger.error(f"获取AI服务状态失败: {e}")
        raise HTTPException(
            status_code=500,
            detail=f"获取AI服务状态失败: {str(e)}"
        )


@router.post("/ai/test-connection")
async def test_ai_connection(request: AITestRequest = None):
    """
    测试AI服务连接
    
    Args:
        request: 测试请求参数
        
    Returns:
        Dict: 连接测试结果
    """
    try:
        result = await ai_service.test_connection()
        
        if result["success"]:
            return {
                "success": True,
                "message": "AI服务连接测试成功",
                "details": result
            }
        else:
            return {
                "success": False,
                "message": "AI服务连接测试失败",
                "error": result.get("error"),
                "details": result.get("details")
            }
            
    except Exception as e:
        logger.error(f"AI连接测试失败: {e}")
        raise HTTPException(
            status_code=500,
            detail=f"AI连接测试失败: {str(e)}"
        )


@router.post("/ai/generate-outline")
async def generate_presentation_outline(request: AIGenerateRequest):
    """
    生成演示文稿大纲
    
    Args:
        request: 生成请求参数
        
    Returns:
        Dict: 生成的大纲结果
    """
    try:
        # 验证输入参数
        if not request.topic or not request.topic.strip():
            raise HTTPException(
                status_code=400,
                detail="演示文稿主题不能为空"
            )
        
        if request.slide_count < 3 or request.slide_count > 50:
            raise HTTPException(
                status_code=400,
                detail="幻灯片数量必须在3-50之间"
            )
        
        # 调用AI服务生成大纲
        result = await ai_service.generate_presentation_outline(
            topic=request.topic.strip(),
            requirements=request.requirements.strip() if request.requirements else None,
            slide_count=request.slide_count
        )
        
        if result["success"]:
            return {
                "success": True,
                "message": "演示文稿大纲生成成功",
                "outline": result["outline"]
            }
        else:
            return {
                "success": False,
                "message": "演示文稿大纲生成失败",
                "error": result.get("error"),
                "raw_response": result.get("raw_response")
            }
            
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"生成演示文稿大纲失败: {e}")
        raise HTTPException(
            status_code=500,
            detail=f"生成演示文稿大纲失败: {str(e)}"
        )


@router.get("/ai/retry-stats")
async def get_retry_statistics():
    """
    获取AI服务重试统计信息
    
    Returns:
        Dict: 重试统计信息
    """
    try:
        from ..utils.retry_handler import default_retry_handler
        
        stats = default_retry_handler.get_retry_stats()
        return {
            "success": True,
            "message": "重试统计信息获取成功",
            "statistics": stats
        }
    except Exception as e:
        logger.error(f"获取重试统计信息失败: {e}")
        raise HTTPException(
            status_code=500,
            detail=f"获取重试统计信息失败: {str(e)}"
        )


@router.post("/ai/reset-stats")
async def reset_retry_statistics():
    """
    重置AI服务重试统计信息
    
    Returns:
        Dict: 重置结果
    """
    try:
        from ..utils.retry_handler import default_retry_handler
        
        default_retry_handler.reset_stats()
        return {
            "success": True,
            "message": "重试统计信息已重置"
        }
    except Exception as e:
        logger.error(f"重置重试统计信息失败: {e}")
        raise HTTPException(
            status_code=500,
            detail=f"重置重试统计信息失败: {str(e)}"
        )


@router.post("/ai/generate-detailed-outline")
async def generate_detailed_presentation_outline(request: AIGenerateRequest):
    """
    使用内容生成器生成详细的演示文稿大纲
    
    Args:
        request: 生成请求参数
        
    Returns:
        Dict: 生成的详细大纲结果
    """
    try:
        # 验证输入参数
        if not request.topic or not request.topic.strip():
            raise HTTPException(
                status_code=400,
                detail="演示文稿主题不能为空"
            )
        
        if request.slide_count < 3 or request.slide_count > 50:
            raise HTTPException(
                status_code=400,
                detail="幻灯片数量必须在3-50之间"
            )
        
        # 创建PPTRequest对象
        ppt_request = PPTRequest(
            topic=request.topic.strip(),
            requirements=request.requirements.strip() if request.requirements else None,
            slide_count=request.slide_count
        )
        
        # 使用内容生成器生成详细大纲
        result = await content_generator.generate_presentation_outline(ppt_request)
        
        if result["success"]:
            return {
                "success": True,
                "message": "详细演示文稿大纲生成成功",
                "outline": result["outline"],
                "metadata": result.get("metadata", {})
            }
        else:
            return {
                "success": False,
                "message": "详细演示文稿大纲生成失败",
                "error": result.get("error")
            }
            
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"生成详细演示文稿大纲失败: {e}")
        raise HTTPException(
            status_code=500,
            detail=f"生成详细演示文稿大纲失败: {str(e)}"
        )


@router.post("/ai/generate-slide")
async def generate_single_slide_content(request: SlideGenerateRequest):
    """
    生成单个幻灯片的详细内容
    
    Args:
        request: 幻灯片生成请求参数
        
    Returns:
        Dict: 生成的幻灯片内容
    """
    try:
        # 验证输入参数
        if not request.title or not request.title.strip():
            raise HTTPException(
                status_code=400,
                detail="幻灯片标题不能为空"
            )
        
        # 构建幻灯片信息
        slide_info = {
            "title": request.title.strip(),
            "type": request.slide_type,
            "slide_number": request.slide_number
        }
        
        # 使用内容生成器生成幻灯片内容
        result = await content_generator.generate_slide_content(
            slide_info=slide_info,
            context=request.context
        )
        
        if result["success"]:
            return {
                "success": True,
                "message": "幻灯片内容生成成功",
                "slide": result["slide"].dict(),
                "metadata": result.get("metadata", {})
            }
        else:
            return {
                "success": False,
                "message": "幻灯片内容生成失败",
                "error": result.get("error")
            }
            
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"生成幻灯片内容失败: {e}")
        raise HTTPException(
            status_code=500,
            detail=f"生成幻灯片内容失败: {str(e)}"
        )


@router.post("/ai/generate-visual-suggestions")
async def generate_visual_suggestions(request: VisualSuggestionRequest):
    """
    为幻灯片生成视觉元素建议
    
    Args:
        request: 视觉建议请求参数
        
    Returns:
        Dict: 视觉元素建议
    """
    try:
        # 验证输入参数
        if not request.slide_title or not request.slide_title.strip():
            raise HTTPException(
                status_code=400,
                detail="幻灯片标题不能为空"
            )
        
        # 创建临时SlideContent对象
        from ..models import SlideType
        try:
            slide_type_enum = SlideType(request.slide_type)
        except ValueError:
            slide_type_enum = SlideType.CONTENT
        
        slide_content = SlideContent(
            title=request.slide_title.strip(),
            content=request.slide_content,
            slide_type=slide_type_enum
        )
        
        # 生成视觉建议
        result = await content_generator.generate_visual_suggestions(
            slide_content=slide_content,
            template_style=request.template_style
        )
        
        if result["success"]:
            return {
                "success": True,
                "message": "视觉元素建议生成成功",
                "visual_suggestions": result["visual_suggestions"],
                "template_style": result["template_style"],
                "slide_type": result["slide_type"]
            }
        else:
            return {
                "success": False,
                "message": "视觉元素建议生成失败",
                "error": result.get("error")
            }
            
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"生成视觉元素建议失败: {e}")
        raise HTTPException(
            status_code=500,
            detail=f"生成视觉元素建议失败: {str(e)}"
        )


@router.post("/ai/optimize-content")
async def optimize_presentation_content(request: ContentOptimizeRequest):
    """
    优化演示文稿内容流程和格式
    
    Args:
        request: 内容优化请求参数
        
    Returns:
        Dict: 优化结果
    """
    try:
        # 验证输入参数
        if not request.slides:
            raise HTTPException(
                status_code=400,
                detail="幻灯片列表不能为空"
            )
        
        # 将字典转换为SlideContent对象
        slide_objects = []
        for slide_data in request.slides:
            try:
                from ..models import SlideType
                slide_type_enum = SlideType(slide_data.get("slide_type", "content"))
                
                slide_content = SlideContent(
                    title=slide_data.get("title", ""),
                    content=slide_data.get("content", []),
                    slide_type=slide_type_enum,
                    visual_elements=slide_data.get("visual_elements", []),
                    notes=slide_data.get("notes"),
                    slide_number=slide_data.get("slide_number", len(slide_objects) + 1)
                )
                slide_objects.append(slide_content)
            except Exception as e:
                logger.warning(f"跳过无效的幻灯片数据: {e}")
                continue
        
        if not slide_objects:
            raise HTTPException(
                status_code=400,
                detail="没有有效的幻灯片数据"
            )
        
        # 优化内容
        result = await content_generator.optimize_content_flow(
            slides=slide_objects,
            optimization_goals=request.optimization_goals
        )
        
        if result["success"]:
            # 将优化后的SlideContent对象转换为字典
            optimized_slides_dict = [
                slide.dict() for slide in result["optimized_slides"]
            ]
            
            return {
                "success": True,
                "message": "内容优化成功",
                "optimized_slides": optimized_slides_dict,
                "optimization_summary": result.get("optimization_summary", {})
            }
        else:
            return {
                "success": False,
                "message": "内容优化失败",
                "error": result.get("error")
            }
            
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"优化演示文稿内容失败: {e}")
        raise HTTPException(
            status_code=500,
            detail=f"优化演示文稿内容失败: {str(e)}"
        )